package com.kylin.system.controller;

import com.kylin.common.core.beans.ResultBean;
import com.kylin.common.log.annotation.Log;
import com.kylin.common.log.enums.BusinessType;
import com.kylin.common.security.util.SecurityUtils;
import com.kylin.system.entity.SysUser;
import com.kylin.system.service.SysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;

/**
 * 个人信息 业务处理
 * 
 * @author wuhao
 */
@RestController
@RequestMapping("/user/profile")
public class SysProfileController
{
    @Autowired
    private SysUserService userService;

    /**
     * 个人信息
     */
    @GetMapping
    public ResultBean<Object> profile()
    {
        String username = SecurityUtils.getUsername();
        SysUser user = userService.selectUserByUserName(username);

        Map<String, Object> data = new HashMap<>();
        data.put("user", user);
        data.put("roleGroup", userService.selectUserRoleGroup(username));
        data.put("postGroup", userService.selectUserPostGroup(username));
        return ResultBean.onSuccess(data);

    }

    /**
     * 修改用户
     */
    @Log(title = "个人信息", businessType = BusinessType.UPDATE)
    @PutMapping
    public ResultBean<Object> updateProfile(@RequestBody @Valid SysUser user)
    {
        userService.update(user);
        return ResultBean.onSuccess();
    }

    /**
     * 重置密码
     */
    @Log(title = "个人信息", businessType = BusinessType.UPDATE)
    @PutMapping("/updatePwd")
    public ResultBean<Object> updatePwd(String oldPassword, String newPassword)
    {
        String username = SecurityUtils.getUsername();
        SysUser user = userService.selectUserByUserName(username);
        String password = user.getPassword();
        if (!SecurityUtils.matchesPassword(oldPassword, password))
        {
            return ResultBean.onFail("修改密码失败，旧密码错误");
        }
        if (SecurityUtils.matchesPassword(newPassword, password))
        {
            return ResultBean.onFail("新密码不能与旧密码相同");
        }
        Long id = SecurityUtils.getUserId();
        if (userService.resetUserPwd(id, SecurityUtils.encryptPassword(newPassword)) > 0)
        {
            return ResultBean.onSuccess();
        }
        return ResultBean.onFail("修改密码异常，请联系管理员");
    }
}
